/* eslint-disable */
import xlsx from './util/xlsx'
import formatClass from './util/formatClass'

let deptMap = {
    部门名称: {col: 'name', required: true},
   
    部门编码: {col: 'code', reg: /^\d+$/, desc: '只允许填写数字'},
    上级部门: {col: 'parentName'}
}

let teacherMap = {
    职工姓名: {col: 'name', required: true},
    性别: {col: 'gender'},
    身份证号码: {col: 'idNumber', reg: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, desc: '身份证号码不正确'},
    手机号码: {col: 'cellPhoneNum', reg: /^1[3456789]\d{9}$/, required: true, desc: '手机号码不正确', noRepeat: true},
    教学科目: {col: 'subJectName', reg: ''},
    授课班级: {col: 'importTeacherClassMaps', reg: '', desc: '班级不正确', isClass: true, isCheckGrade: true},
    担任班主任班级: {col: 'masterClass', reg: '', desc: '班级不正确', isClass: true, isCheckGrade: true},
    所在部门: {col: 'deptNameList', reg: ''}
}
// /^((([0-9一二三四五六七八九]年级)|(高[123一二三]))[0-9一二三四五六七八九]+班[，、,\.]?)*$/
let studentMap = {
    学生姓名: {col: 'name', reg: '', required: true},
    学籍号: {col: 'studentCode', reg: '', noRepeat: true},
    身份证号码: {col: 'idNumber', reg: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, desc: '身份证号码不正确', noRepeat: true},
    性别: {col: 'gender', reg: ''},
    所属学段: {col: 'stageName', required: true, reg: '', list: [], isListNum: false},
    学级: {col: 'startYear', reg: '', required: true, list: [], isListNum: true},
    年级: {col: 'gradeName', required: true, list: [], isListNum: false, isClass: true},
    班级: {col: 'className', reg: /^[0-9一二三四五六七八九]+班$/, desc:'格式如：1班', required: true, isClass: true},
    入学年月: {col: 'startDate', reg: /^[0-9]{4}[\/\.-]{1}[0-9]{1,2}$/, desc: '格式如：2020-01', required: true},

    
    家长姓名: {col: 'parentName', reg: '', required: true},
    家长手机号码: {col: 'parentPhone',  reg: /^1[3456789]\d{9}$/, required: true, desc: '手机号码不正确'},
    关系: {col: 'relationCode', reg: '', list: [], isListNum: false}
}

function Map() {
    
}

Map.prototype.check = function({required, reg, desc, val, col, list, isListNum, isCheckGrade, dataList, noRepeat}){
    if (required) {
        if (!val) {
            return {legal: false, desc: '不能为空'}
        }
    }

    if (list && val) {
        console.log(list)
        var isHave = false
        for (var item of list) {
            if (isListNum) {
                if (this.getNumber(item) == this.getNumber(val)) {
                    isHave = true
                }
            } else {
                if (item == val) {
                    isHave = true
                }
            }
            
        }
        console.log('isHave:', isHave)
        return  {legal: isHave, desc: '不存在的值'}
    }

    if (reg && val) {
        if (!reg.test(val)) {
            return  {legal: false, desc: desc}
        }
    }

    if (isCheckGrade && val) {
        if (!this.checkGrade(val)) {
            return {legal: false, desc: '班级不正确'}
        }
    }

    return {legal: true, desc: ''}
}

Map.prototype.checkList = function({list, map}){
    
    var data = [].concat(list)
    console.log('dataList:', data)
    for (var item of data) {              
        for (var key in map) {
            var col = map[key].col
            
            // 学级
            if (col == 'startYear') {
                
                var list = this.getPeroidsByStageName(item.stageName.val)
            } else if (col == 'gradeName') {
                
                var list = this.getGradeByName({stageName: item.stageName.val, peroidName: item.startYear.val})
            } else {
                var list = map[key].list
            }
            map[key].list = list
           
            var multiple = map[key].multiple
           
            
            var checkObj =  Object.assign({}, map[key]) 
            checkObj.val = item[col].val
            checkObj.dataList = data
            
         
            var result = this.check(checkObj)
            item[col].legal = result.legal
            item[col].desc = result.desc

            if (list) {
                item[col].list = list
                item[col].multiple = multiple
            }
        }
    }
    return data
}

Map.prototype.checkGrade = function(str){
    var reg = /^([0-9一二三四五六七八九]年级)|(高[123一二三](年级)?).*$/
    var strList = this.splitByAll(str)

    var flag = true
    for (var item of strList) {
        var result = reg.exec(item)
        var g = ''
        if (result && result[1]) {
            g = result[1]
        }
        if (result && result[2]) {
            g = result[2]
        }
        
        if (!this.gradeList.includes(g)) {
            flag = false
        }
    }
    
    return flag
}

Map.prototype.clearItem = function(item){
    for (var key in item) {
        var val = item[key]
        key = key.replace(/[\s\*]+/g, '')

        if (!val) {
            val = ''
        }
        val = (val + '').replace(/\s+/g, '')
        item[key] = val
    }
}

Map.prototype.toEnglish = function({data, map}){
    
    var list = []
        
    for (var item of data) {
        this.clearItem(item)
        var obj = {}
        for (var key in map) {
            var val = item[key]
            if (!val) {
                val = ''
            }
          
            var col = map[key].col
                
            obj[col] = val
        }
        list.push(obj)
    }
    return list
}

Map.prototype.convert = function({data, map}){
    
    var list = []
        
    for (var item of data) {
        this.clearItem(item)
        var obj = {}
        for (var key in map) {
            var val = item[key]
            if (!val) {
                val = ''
            }

            if (map[key].isClass) {
                val = formatClass(val)
            }
            if (map[key].isArr) {
                val = this.splitByAll(val)
            }

          
            var col = map[key].col
                
            obj[col] = {
                val: val,
                ch: key
            }
        }
        list.push(obj)
    }
    return list
}

Map.prototype.createData = function({data, map}){
    var list = this.convert({data, map})
    list = this.checkList({list, map})
    return list
}
Map.prototype.readData = async function({file, fileId, check, map}){
    var res = await xlsx.read(file)
    if (check) {
        var list = this.createData({data: res, map})
    
        for (var item of list) {
            item.fileId = fileId
            item.id = this.uuid()
        }
    } else {
        var list = this.toEnglish({data: res, map})
    }
    return list
}

Map.prototype.uuid = function(){
	var s = [];
	var hexDigits = "0123456789abcdef";
	for (var i = 0; i < 36; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	}
	s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
	s[8] = s[13] = s[18] = s[23] = "-";

	var uuid = s.join("");
	return uuid;
}

Map.prototype.formatData = function(list){
    list = JSON.parse(JSON.stringify(list))
    for (var item of list) {
        delete item.id
        delete item.fileId
        for (var key in item) {
            if (typeof item[key] == 'object') {
                item[key] = item[key].val
            }
            item[key] = item[key].replace(/\s+/g, '')
        }
    }
    return list
}

Map.prototype.splitByAll = function(str){
    var arr = str.split(/[,.，。、\/]/)
    for (var i = arr.length - 1; i >= 0; i--) {
        if (!arr[i]) {
            arr.splice(i, 1)
        }
    }
    return arr
}
Map.prototype.formateDate = function(str){
    
    str = str.replace(/\//g, '-')
    
    var date = new Date(str)
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    if (month < 10) {
        month = '0' + month
    }
    var d = date.getDate()
    d = d < 10 ? '0' + d : d
    var hour = date.getHours()
    hour = hour < 10 ? '0' + hour : hour
    var minute = date.getMinutes()
    minute = minute < 10 ? '0' + minute : minute
    var sec = date.getSeconds()
    sec = sec < 10 ? '0' + sec : sec
    return year + '-' + month + '-' + d + ' '+hour+':'+minute+':' + sec
}

Map.prototype.getNumber = function(str){
    var num= str.replace(/[^0-9]/ig,"")
    return num
}

export default Map
